package com.xyc.login.controller;

import com.xyc.common.utils.SecurityUtils;
import com.xyc.user.entity.User;
import com.xyc.user.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.security.NoSuchAlgorithmException;

@Controller
@RequestMapping("login")
public class LoginController {

    @Autowired
    private UserService userService;

    /**
     * @Author xyc
     * @Date 2017/9/9/009 下午:17:19
     * @Description 登录页面
     */
    @RequestMapping
    public String login() {

        return "login";
    }

    /**
     * @Author xyc
     * @Date 2017/9/9/009 下午:17:20
     * @Description 校验登录
     */
    @RequestMapping("/check")
    @ResponseBody
    public String checkLogin(HttpServletRequest request) throws UnsupportedEncodingException, NoSuchAlgorithmException {

        String username = request.getParameter("username");
        String password = request.getParameter("password");

        //查数据库
        User user = userService.findUserByUserName(username);
        if (user != null) {
           if (SecurityUtils.checkPassword(password,user.getPassword())){
               //校验成功 设置session
               request.getSession().setAttribute("userinfo",user);
               return "login_success";
           }else {
               return "login_fail";
           }

        } else {
            return "login_fail";
        }

        //用户信息存session 进入首页
        //校验失败

    }

    @RequestMapping("/register")
    @ResponseBody
    public String register(@RequestBody User user) throws UnsupportedEncodingException, NoSuchAlgorithmException {
        userService.createUser(user);
        return "success";

    }
}
